Brief Full Advanced Search Search Tips
|  |  | To access the contents, click the chapter and section titles. Visual Basic 6 Programming Blue Book: The Most Complete, Hands-On Resource for Writing Programs with Microsoft Visual Basic 6! (Publisher: The Coriolis Group) Author(s): Peter G. Aitken ISBN: 1576102815 Publication Date: 08/01/98 Search this book:
Previous | Table of Contents | Next
## Part 6 Final Touches ## Chapter 25 Error Handling This is one of the shortest chapters in the book, and you may think it’s one of the least interesting. In truth, it may be the most important. Writing error-handling code is undoubtedly the least interesting part of programming. The code doesn’t do anything exciting or flashy—no multimedia extravaganzas, no lightning-fast math calculations, no clever user interfaces—but the fact remains that a program without well-designed and carefully implemented error-handling code is almost guaranteed to have its users clamoring for the programmer’s blood, your blood. Pay attention to this chapter, and you may live to a ripe old age. ### What Errors Need Handling? Computer programs are rife with possibilities for errors. In fact, several different categories of errors can occur. Syntax errors happen when you make a mistake writing the program: using an undeclared variable (only when using Option Explicit, of course, which you always should do), passing the wrong number and/or type of arguments to a function, or misspelling a function name. Pesky as these types of errors are, they are rarely serious problems. Visual Basic catches them as soon as you try to run the program in the Visual Basic development environment. Depending on the specific error, Visual Basic will highlight the offending line of code or display a dialog box with a description of the error. In the latter case, click on the Debug button to go to the line of code where the error occurred. These built-in capabilities make finding and fixing syntax errors easy; they almost never survive in a program to cause problems for the end user. Other types of errors, however, are not dealt with so easily. They usually don’t make themselves known during program development when you can easily fix them. Rather, they wait until the program is in the hands of the end user. Why are these errors so tough to handle? Because they usually depend on factors that are out of your control. Here are a few examples: • The program prompts the user to enter a number, but he or she enters a string instead. • The program tries to read from a file that has been deleted. • The user enters data that results in an attempt to divide by zero. • The program tries to write data to drive A: with no diskette inserted in the drive. • The program tries to access a network file when the user does not have sufficient access rights. The list could go on and on. Literally hundreds of these runtime errors are possible, and no programmer—regardless of how clever—can guarantee that none of them will occur. The programmer’s job is to provide error-handling code in the program, ensuring that any errors that do crop up will not have serious consequences for the user. This task is done using Visual Basic’s error-trapping capabilities. What happens if you don’t trap errors? If the program is running in the Visual Basic development environment, most errors result in the display of a dialog box describing the error, as shown in Figure 25.1. The dialog box displays the error number and a brief description of the error. The program at this point is suspended. If you click on the End button in the dialog box, the program terminates. If you click on Debug, the program remains suspended and the cursor is positioned on the line of code that caused the error. You can edit the code to try to eliminate the error, then press F5 to continue the program execution where it stopped. (Certain types of changes to the code do not permit continuing program execution; they require the program to be restarted. Visual Basic informs you when this is the case.) If you are running the Visual Basic program as a standalone EXE file, untrapped errors are also reported by a dialog box giving the error number and a brief description. Of course, you don’t have the option to edit the code to correct the error. Because end users will be executing your program as a standalone, whenever an untrapped error occurs, they are faced with a terse message and a nonfunctional program. Proper error trapping will let you avoid this situation. Figure 25.1 Untrapped errors are reported in Visual Basic by a dialog box. #### Trapping Errors Trapping errors is similar in some respects to handling events. If you think of an error as an event, and error-handling code as an event procedure, you’ll have a good start toward understanding how Visual Basic deals with errors. The difference is that an error does not trigger a discrete event procedure. Rather, you use the On Error statement to specify the exact code location where execution is supposed to pass when an error occurs. Here’s an example. The statement
    On Error Goto ErrorHandler
tells Visual Basic that when an error occurs, execution passes to the line of code identified by the label ErrorHandler. Labels that identify locations in code consist of a name followed by a colon, as shown in these three examples:
    ErrorHandler:
    IfError:
    OJSimpson:
The rules for line labels are the same as for Basic variable names—the only difference is the colon at the end. Each procedure’s error-handling code is traditionally placed at the end of the procedure, between the last “regular” statement in the procedure and the End Sub or End Function statement at the end. You must place an Exit Sub or Exit Function statement just before the label identifying the error-handling code to prevent execution from falling into the error-handling code. Here are the basics:
    Sub MySub()

    On Error Goto Errorhandler

    ' Procedure statements go here.

    Exit Sub

    Errorhandler:

    ' Error handling code goes here.

    End Sub
The line label identifying the error-handling code must be in the same procedure as the On Error Goto statement that specifies it. This means that error-handling code is local to procedures (both event and general procedures). You might think that this is a bad idea; wouldn’t it be better to have a single comprehensive error handler that deals with errors occurring in all parts of the program? Not really. Because each procedure tends to deal with one discrete aspect of the program (at least if you’re programming properly), the type of errors it could possibly generate will be limited. For instance, a Text Box’s Change event procedure may need to deal with improper data entry, but it will never be faced with a disk access or printer error. Therefore, each procedure’s error-handling code can be relatively simple and concise—dealing only with that procedure’s potential errors. In addition, by including error-handling code in procedures, each procedure becomes an independent entity that is not dependent on code elsewhere in the program. There are two variants of the On Error statement. The statement
    On Error Goto 0
causes error trapping to be disabled; the program will respond to errors in the default manner by displaying the terse dialog box described previously. The statement
    On Error Resume Next
instructs the program to ignore the error temporarily and to continue executing with the statement immediately following the one that caused the error. This does not mean that you are ignoring the error (a bad idea, to be sure), but that you are deferring handling of the error for the moment. This technique is used in situations where the information needed to diagnose the error accurately is not immediately available. Now you know how to trap errors by directing program execution to a special section of code when an error occurs. Several burning questions remain to be answered: for example, how do you know which error has occurred, and what can you do about it? I’ll deal with these questions soon; first, let’s look at a sample procedure that contains error-trapping code, just to give you a feel for how it works. This sample procedure is presented in Listing 25.1. The comments in the code explain how it works. This procedure contains no real code, just the error-trapping statements and comments. Listing 25.1 How error trapping works.
    Private Sub MyDemoProcedure()

    ' At this point in the code, before any On Error has been executed,
    ' errors will be reported by a dialog box in the default fashion.

    On Error Go To ErrorHandler:

    ' In this section of code, when an error occurs, execution will
    ' pass to the location identified by the ErrorHandler label.

    On Error Goto 0

    ' In this section of code, error trapping is disabled. Errors
    ' will be reported to the user in the default dialog box format.

    On Error Resume Next

    ' In this section of code, error trapping is deferred.

    On Error Go To ErrorHandler:

    ' In this section, error trapping is again directed to the code
    ' following the ErrorHandler label.

    Exit Sub

    ' The Exit Sub is required so execution does not fall into the
    ' following error handling code.

    ErrorHandler:

    ' The error handling code is placed here.

    End Sub
#### The Resume Statement The Resume statement is used within error-handling code to instruct the program where to continue execution after the error has been handled. Resume can be used only within error-handling code; otherwise, an error occurs. There are several variants of Resume. When used by itself, it means “try again to execute the statement that caused the error.” This is appropriate in situations where the cause of the error has been fixed. In other circumstances, however, this is not possible. If you want execution to continue somewhere other than the statement that caused the error, you have the following two choices: • Resume Next continues execution immediately after the statement that caused the error. • Resume label continues execution with the program line identified by label. The line identified by label must be in the same procedure as the Resume statement (the same procedure where the error occurred). I will provide more information later on deciding which of the Resume statements you should use.
Previous | Table of Contents | Next

| Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.